﻿using System;
using System.Collections.Generic;
using System.Linq;
namespace AlgorithmExercise
{
    class Program
    {
        static void Main(string[] args)
        {
            //new Introduction.MergeSort().Run();
            Console.Write(LengthOfLongestSubstring("dvdf"));
            Console.ReadKey();
        }

        public static int LengthOfLongestSubstring(string s)
        {
            var array = s.ToCharArray();
            int n = array.Length, ans = 0;
            Dictionary<char, int> map = new Dictionary<char, int>();
            for (int j = 0, i = 0; j < n; j++)
            {
                if (map.ContainsKey(array[j]))
                {
                    i = Math.Max(map[array[j]], i);
                }
                ans = Math.Max(ans, j - i + 1);
                map[array[j]] = j + 1;
            }
            return ans;
        }

        public static int LengthOfLongestSubstring1(string s)
        {
            var array = s.ToCharArray();
            var result = new HashSet<char>();
            var length = array.Length;
            int maxLength = 0;
            int i = 0, j = 0;
            while (i < length & j < length)
            {
                if (!result.Contains(array[j]))
                {
                    result.Add(array[j]);
                    int temp = result.Count;
                    if (maxLength < temp)
                    {
                        maxLength = temp;
                    }
                    j++;
                }
                else
                {
                    result.Remove(array[i++]);
                }
            }
            return maxLength;
        }

        public static int LengthOfLongestSubstring2(string s)
        {
            int maxLength = 0;
            for (int i = 0; i < s.Length; i++)
            {
                if (maxLength > s.Length - i) { break; }
                // result.Add(i,s.Substring(i,1));
                string resultTemp = s.Substring(i, 1);
                if (i < s.Length - 1)
                {
                    for (int j = i + 1; j < s.Length; j++)
                    {
                        string temp = s.Substring(j, 1);
                        if (!resultTemp.Contains(temp))
                        {
                            resultTemp += temp;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
                if (maxLength < resultTemp.Length)
                {
                    maxLength = resultTemp.Length;
                }

            }
            return maxLength;
        }
    }
}
